//mainwindow.cc
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    socket = new QTcpSocket();          //实例化tcp客户端
    ti = new QTimer();                  //定时器
    sizz = 0;
    sizz2 = 0;
    //连接信号槽
    QObject::connect(socket, &QTcpSocket::readyRead, this, &MainWindow::socket_Read_Data);
    ui->lineEdit_IP->setText("192.168.4.1");        //ip地址
    ui->lineEdit_Port->setText("8080");         //端口号

    connect(ti , SIGNAL(timeout()) , this , SLOT(timeshow()));
    ti->start(1000);
    initChart();
    initChart_openfile();
}
void MainWindow::timeshow()         //发送时间到单片机
{
    tim = QDateTime::currentDateTime();
    ui->dateTimeEdit->setDateTime(tim);
}
void MainWindow::initfile()                     //初始化文件
{
    bool res;
    QString tim1 = tim.toString("yyyy-MM-dd-hh-mm-ss");
    QString namevoc = tim1 + "-TVOC.txt";
    QString nameco2 = tim1 + "-CO2.txt";
    QString nametm =tim1 + "-温度.txt";
    QString namehu =tim1 + "-湿度.txt";
    QString namenh3 =tim1 + "-NH3.txt";
    filevoc = new QFile();
    filevoc->setFileName(namevoc);
    res = filevoc->open(QIODevice::ReadWrite|QIODevice::Text);       //打开文件
    qDebug()<<"voc------------------"<<res;
    fileco2 = new QFile();
    fileco2->setFileName(nameco2);
    res = fileco2->open(QIODevice::ReadWrite|QIODevice::Text);       //打开文件
    qDebug()<<"co2------------------"<<res;
    filetm = new QFile;
    filetm->setFileName(nametm);
    res = filetm->open(QIODevice::ReadWrite|QIODevice::Text);
    qDebug()<<"tm------------------"<<res;
    filehumi = new QFile;
    filehumi->setFileName(namehu);
    res = filehumi->open(QIODevice::ReadWrite|QIODevice::Text);
    qDebug()<<"hu------------------"<<res;
    filenh3 = new QFile;
    filenh3->setFileName(namehu);
    res = filenh3->open(QIODevice::ReadWrite|QIODevice::Text);
    qDebug()<<"nh3------------------"<<res;
    //out = new QTextStream(fileph);out1 = new QTextStream(filetm);out2 = new QTextStream(filehumi);
}

MainWindow::~MainWindow()
{
    delete this->socket;
    if(filevoc->isOpen())
    {
        filevoc->close();
    }
    if(filetm->isOpen())
    {
        filetm->close();
    }
    if(filehumi->isOpen())
    {
        filehumi->close();
    }
    if(fileco2->isOpen())
    {
        fileco2->close();
    }
    if(filenh3->isOpen())
    {
        filenh3->close();
    }
    delete ui;
}

void MainWindow::on_pushButton_Connect_clicked()
{
    if(ui->pushButton_Connect->text() == tr("连接"))
    {
        QString IP;
        int port;

        //获取IP地址
        IP = ui->lineEdit_IP->text();
        //获取端口号
        port = ui->lineEdit_Port->text().toInt();

        //取消已有的连接
        socket->abort();
        //连接服务器
        socket->connectToHost(IP, port);

        //等待连接成功
        if(!socket->waitForConnected(30000))
        {
            qDebug() << "Connection failed!";
            return;
        }
        qDebug() << "Connect successfully!";
        //修改按键文字
        ui->pushButton_Connect->setText("断开连接");
        initfile();
    }
    else
    {
        //断开连接
        socket->disconnectFromHost();
        //修改按键文字
        ui->pushButton_Connect->setText("连接");
        filevoc->close();
        fileco2->close();
        filetm->close();
        filehumi->close();
        filenh3->close();
    }
}

void MainWindow::socket_Read_Data()
{
    QString recvdata = socket->readAll();
    qDebug() << recvdata;
    QString tm;
    if(recvdata.isEmpty() || recvdata.size()<4)
        return;
    QStringList list = recvdata.split(',');
    if(list.size() < 3)
        return;
    ui->lineEdit->setText(list[0]);
    voc = list[0];
    if(list[1].toDouble() <= 100 && list[1].toDouble() >= 0)
    {
        ui->lineEdit_4->setText(list[1]);
        co2 = list[1];
    }
    ui->lineEdit_2->setText(list[2]);
    tmm = list[2];
    ui->lineEdit_3->setText(list[3]);
    hii = list[3];
    ui->lineEdit_5->setText(list[4]);
    nh3 = list[4];
    sizz++;
    if(sizz == 20)                  //20个字符之后将容器清空，容器存储太多会卡
    {
        sizz = 0;
        x.clear();
        y.clear();
        y_2.clear();
        x_tm.clear();
        y_tm.clear();
        y_hi.clear();
        ui->widget->graph(0)->data().data()->clear();
        ui->widget->graph(1)->data().data()->clear();
        ui->widget->graph(2)->data().data()->clear();
        ui->widget->graph(3)->data().data()->clear();
        ui->widget->graph(4)->data().data()->clear();
        ui->widget->replot();
    }
    x.append(sizz);            //将获取到的时间进行格式整理并转换为double类型
    y.append(voc.toDouble());
    y_2.append(tmm.toDouble());
    x_tm.append(hii.toDouble());
    y_tm.append(co2.toDouble());
    y_hi.append(nh3.toDouble());

    graph1->addData(x ,y);      //添加绘图的线
    graph2->addData(x ,y_2);      //添加绘图的线
    graph3->addData(x ,x_tm);      //添加绘图的线
    graph4->addData(x ,y_tm);      //添加绘图的线
    graph5->addData(x ,y_hi);      //添加绘图的线
    ui->widget->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
    ui->widget->replot();

    filevoc->write(voc.toStdString().c_str());
    filevoc->write("\n");

    fileco2->write(co2.toStdString().c_str());
    fileco2->write("\n");

    filetm->write(tmm.toStdString().c_str());
    filetm->write("\n");

    filehumi->write(hii.toStdString().c_str());
    filehumi->write("\n");

    filenh3->write(nh3.toStdString().c_str());
    filenh3->write("\n");
    //*out << phh<<endl;
}


void MainWindow::initChart_openfile()               //初始化打开文件的画板
{
    ui->widget_2->axisRect()->setBackground(QBrush(Qt::black));

    ui->widget_2->legend->setVisible(true);
    ui->widget_2->xAxis->setLabel("Time(s)");//设置ｘ轴
    ui->widget_2->xAxis->setTicks(true);

    ui->widget_2->yAxis->setLabel("%/℃");//设置ｙ轴
    ui->widget_2->yAxis->setTicks(true);


    graph_1 = ui->widget_2->addGraph();//增加一条曲线图层



    QCPScatterStyle QCPcs1(QCPScatterStyle::ssSquare, QColor(255,0,0),QColor(255,0,0),3);//设置折线图的点的形状及颜色
    QPen qPen1(QColor(255,0,0));
    graph_1->setScatterStyle(QCPcs1);
    graph_1->setPen(qPen1);//设置画笔颜色
    graph_1->setName(QString("data"));

    ui->widget_2->xAxis->ticker()->setTickCount(11);//11个主刻度
    ui->widget_2->xAxis->ticker()->setTickStepStrategy(QCPAxisTicker::tssReadability);


    ui->widget_2->yAxis->ticker()->setTickCount(11);

    ui->widget_2->yAxis->setRangeLower(0);
    ui->widget_2->xAxis->setRangeLower(0);
    ui->widget_2->xAxis->setRangeUpper(50);
    ui->widget_2->yAxis->setRangeUpper(100);
}


void MainWindow::initChart()            //初始化的实时检测
{
    ui->widget->axisRect()->setBackground(QBrush(Qt::black));

    ui->widget->legend->setVisible(true);
    ui->widget->xAxis->setLabel("Time(s)");//设置ｘ轴
    ui->widget->xAxis->setTicks(true);

    ui->widget->yAxis->setLabel("%/℃");//设置ｙ轴
    ui->widget->yAxis->setTicks(true);


    graph1 = ui->widget->addGraph();//增加一条曲线图层
    graph2 = ui->widget->addGraph();//增加一条曲线图层
    graph3 = ui->widget->addGraph();//增加一条曲线图层
    graph4 = ui->widget->addGraph();//增加一条曲线图层
    graph5 = ui->widget->addGraph();//增加一条曲线图层

    QCPScatterStyle QCPcs1(QCPScatterStyle::ssSquare, QColor(255,0,0),QColor(255,0,0),3);//设置折线图的点的形状及颜色
    QPen qPen1(QColor(255,0,0));
    graph1->setScatterStyle(QCPcs1);
    graph1->setPen(qPen1);//设置画笔颜色
    graph1->setName(QString("TVOC"));


    QCPScatterStyle QCPcs4(QCPScatterStyle::ssCircle, QColor(0,255,0),QColor(0,255,0),3);//设置折线图的点的形状及颜色
    QPen qPen4(QColor(0,255,255));
    graph4->setScatterStyle(QCPcs4);
    graph4->setPen(qPen4);//设置画笔颜色
    graph4->setName(QString("CO2"));

    QCPScatterStyle QCPcs5(QCPScatterStyle::ssSquare, QColor(0,0,255),QColor(0,0,255),3);//设置折线图的点的形状及颜色
    QPen qPen5(QColor(255,255,0));
    graph5->setScatterStyle(QCPcs5);
    graph5->setPen(qPen5);//设置画笔颜色
    graph5->setName(QString("other"));

    QCPScatterStyle QCPcs2(QCPScatterStyle::ssCircle, QColor(0,255,255),QColor(0,255,255),3);//设置折线图的点的形状及颜色
    QPen qPen2(QColor(0,255,0));
    graph2->setScatterStyle(QCPcs2);
    graph2->setPen(qPen2);//设置画笔颜色
    graph2->setName(QString("温度"));

    QCPScatterStyle QCPcs3(QCPScatterStyle::ssCircle, QColor(255,255,0),QColor(255,255,0),3);//设置折线图的点的形状及颜色
    QPen qPen3(QColor(0,0,255));
    graph3->setScatterStyle(QCPcs3);
    graph3->setPen(qPen3);//设置画笔颜色
    graph3->setName(QString("湿度"));

    ui->widget->xAxis->ticker()->setTickCount(11);//11个主刻度
    ui->widget->xAxis->ticker()->setTickStepStrategy(QCPAxisTicker::tssReadability);
    ui->widget->yAxis->ticker()->setTickCount(11);

    ui->widget->yAxis->setRangeLower(0);
    ui->widget->xAxis->setRangeLower(0);
    ui->widget->xAxis->setRangeUpper(20);
    ui->widget->yAxis->setRangeUpper(100);
}


bool MainWindow::loadFile(const QString& filename) {        //选择文件
    read_voc.clear();
    QFile file(filename);
    if (!file.open(QFile::ReadOnly | QFile::Text)) {
        QMessageBox::warning(this, tr("多文档编辑器"), tr("无法读取文件: %1 \n %2").arg(filename).arg(file.errorString()));
        return false;
    }
    QTextStream in(&file);                          //构造一个指向file文件的QTextStream对象,输入数据流
    QApplication::setOverrideCursor(Qt::WaitCursor);//鼠标保持旋转状态
    //将文件内容读取出来,并写入在ui编辑器中.
    while(!in.atEnd())
    {
        read_voc.append(in.readLine().toDouble());
    }
    return true;
}

void MainWindow::on_pushButton_clicked()
{
    QString FileName = QFileDialog::getOpenFileName(this,tr("请选择需要打开的文件"),"","*.txt");
    if (!FileName.isEmpty()) {
        if(loadFile(FileName))
        {
            QVector<double>x_pp;
            for(int i = 0;i<read_voc.size();i++)
            {
                x_pp.append(i);
            }
            qDebug()<<read_voc;
            if(!read_voc.isEmpty())
            {
                graph_1->setData(x_pp,read_voc);
                ui->widget->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
                ui->widget_2->replot();
            }
        }
    }

}

void MainWindow::on_pushButton_2_clicked()
{
    QWidget *widget = new QWidget;
    QTextEdit *edit = new QTextEdit(widget);
    edit->setGeometry(widget->geometry());
    if(!read_voc.isEmpty())
    {
        for(auto i : read_voc)
        {
            edit->append(QString::number(i));
        }
        widget->show();
    }
}
